package com.ad.backstage.service.impl;

import com.ad.backstage.common.constant.Const;
import com.ad.backstage.common.exception.BackStageRuntimeException;
import com.ad.backstage.common.utils.BeanUtil;
import com.ad.backstage.mapper.ItemCategoryMapper;
import com.ad.backstage.mapper.ItemDetailMapper;
import com.ad.backstage.mapper.UploadRecordMapper;
import com.ad.backstage.model.ItemCategory;
import com.ad.backstage.model.ItemDetail;
import com.ad.backstage.model.UploadRecord;
import com.ad.backstage.service.ItemSystemService;
import com.ad.backstage.service.UploadService;
import com.ad.payload.dto.item.*;
import com.ad.payload.enums.BusinessTypeEnum;
import com.ad.payload.enums.DeleteStatusEnum;
import com.ad.payload.model.IdDto;
import com.ad.payload.model.PageView;
import com.ad.payload.util.StringUtil;
import com.ad.payload.vo.item.ImgVo;
import com.ad.payload.vo.item.ItemCategoryVo;
import com.ad.payload.vo.item.ItemDetailVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections4.QueueUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.prefs.BackingStoreException;
import java.util.stream.Collectors;

/**
 * @author:dxgong
 * @日期 2021/4/17 20:11
 * @注释
 */
@Service
public class ItemSystemServiceImpl implements ItemSystemService{


    @Autowired
    private ItemCategoryMapper itemCategoryMapper;

    @Autowired
    private ItemDetailMapper itemDetailMapper;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private UploadRecordMapper uploadRecordMapper;


    /**
     * 分页产品类目
     *
     * @param itemCategorySearchDto
     */
    @Override
    public PageView<ItemCategoryVo> pageItemCategory(ItemCategorySearchDto itemCategorySearchDto) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("merchant_id", itemCategorySearchDto.getMerchantId());
        IPage<ItemCategory> iPage =
                itemCategoryMapper.selectPage(new Page<>(itemCategorySearchDto.getPageNo(), itemCategorySearchDto.getPageSize()), queryWrapper);

        PageView pageView = new PageView(iPage);

        List<ItemCategory> records = iPage.getRecords();
        List<ItemCategoryVo> list = new ArrayList<>();

        records.forEach(item -> {
            ItemCategoryVo itemCategoryVo = new ItemCategoryVo();
            BeanUtil.copyProperties(item, itemCategoryVo);
            list.add(itemCategoryVo);
        });

        pageView.setPageList(list);

        return pageView;
    }

    /**
     * 添加产品类目
     *
     * @param itemCategoryAddDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addItemCategory(ItemCategoryAddDto itemCategoryAddDto) {
        ItemCategory itemCategory = new ItemCategory();
        BeanUtil.copyProperties(itemCategoryAddDto, itemCategory);
        itemCategoryMapper.insert(itemCategory);
        return String.valueOf(itemCategory.getId());
    }

    /**
     * 更新产品类目
     *
     * @param itemCategoryEditDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateItemCategory(ItemCategoryEditDto itemCategoryEditDto) {
        ItemCategory itemCategory = new ItemCategory();
        BeanUtil.copyProperties(itemCategoryEditDto, itemCategory);
        itemCategoryMapper.updateById(itemCategory);
        return String.valueOf(itemCategoryEditDto.getId());
    }

    /**
     * 删除产品类目
     *
     * @param idDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long deleteItemCategory(IdDto idDto) {
        itemCategoryMapper.deleteById(idDto.getId());
        return idDto.getId();
    }

    /**
     * 根据id查询产品类目
     *
     * @param idDto
     */
    @Override
    public ItemCategoryVo queryItemCategoryById(IdDto idDto) {
        ItemCategory itemCategory = itemCategoryMapper.selectById(idDto.getId());
        ItemCategoryVo itemCategoryVo = new ItemCategoryVo();
        BeanUtil.copyProperties(itemCategory, itemCategoryVo);
        return itemCategoryVo;
    }

    /**
     * 分页查询产品
     *
     * @param itemDetailSearchDto
     */
    @Override
    public PageView<ItemDetailVo> pageItemDetailVo(ItemDetailSearchDto itemDetailSearchDto) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("class_id", itemDetailSearchDto.getClassId());
//        queryWrapper.eq("merchant_id", itemDetailSearchDto.getMerchantId());

        IPage iPage = itemDetailMapper.selectPage(new Page<>(itemDetailSearchDto.getPageNo(), itemDetailSearchDto.getPageSize()), queryWrapper);

        PageView pageView = new PageView(iPage);

        List pageList = pageView.getPageList();
        List<ItemDetailVo> list = new ArrayList<>();

        pageList.forEach(item -> {
            ItemDetailVo itemDetailVo = new ItemDetailVo();
            BeanUtil.copyProperties(item, itemDetailVo);

            List<UploadRecord> uploadRecords = uploadService.queryUploadRecordByBusinessId(itemDetailVo.getId());
            if(uploadRecords.size() != 0){

                List<UploadRecord> collect =
                        uploadRecords.stream().filter(predicate
                                -> BusinessTypeEnum.ITEM_COVER.getValue().equals(predicate.getBusinessType())).collect(Collectors.toList());
                UploadRecord uploadRecord = collect.get(0);
                itemDetailVo.setCoverImg(uploadRecord.getPath());
            }
            list.add(itemDetailVo);
        });
        pageView.setPageList(list);
        return pageView;
    }

    /**
     * 新增产品
     *
     * @param itemDetailAddDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long insertItemDetail(ItemDetailAddDto itemDetailAddDto) {
        ItemDetail itemDetail = new ItemDetail();
        BeanUtil.copyProperties(itemDetailAddDto, itemDetail);
        itemDetailMapper.insert(itemDetail);

        // 处理图片
        String imgJson = itemDetailAddDto.getImgJson();
        JSONArray objects = JSON.parseArray(imgJson);

        if(objects.size() == 0){
            throw new BackStageRuntimeException("请至少上传一张图片");
        }
        UploadRecord uploadRecord = new UploadRecord();
        uploadRecord.setBusinessId(itemDetail.getId());
        objects.forEach(item -> {
            // 更新business_id
            String[] imgArr = StringUtil.splits(item.toString(), Const.IMG_SPLIT);
            String id = imgArr[0];
            uploadRecord.setId(Long.valueOf(id));
            uploadRecordMapper.updateById(uploadRecord);
        });

        String detailImgJson = itemDetailAddDto.getDetailImgJson();
        JSONArray detailObjects = JSON.parseArray(detailImgJson);

        if(detailObjects.size() == 0){
            throw new BackStageRuntimeException("请至少上传一张图片");
        }
        UploadRecord detailUploadRecord = new UploadRecord();
        detailUploadRecord.setBusinessId(itemDetail.getId());
        detailObjects.forEach(item -> {
            // 更新business_id
            String[] imgArr = StringUtil.splits(item.toString(), Const.IMG_SPLIT);
            String id = imgArr[0];
            detailUploadRecord.setId(Long.valueOf(id));
            uploadRecordMapper.updateById(detailUploadRecord);
        });

        // uploadRecord.setBusinessId(itemDetailAddDto.getClassId());
        return itemDetail.getId();
    }

    /**
     * 更新产品
     *
     * @param itemDetailEditDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long updateItemDetail(ItemDetailEditDto itemDetailEditDto) {
        ItemDetail itemDetail = new ItemDetail();
        BeanUtil.copyProperties(itemDetailEditDto, itemDetail);
        itemDetailMapper.updateById(itemDetail);

        // 处理图片, 删掉原来的重新插入
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("business_id", itemDetailEditDto.getId());
        UploadRecord deleteRecord = new UploadRecord();
        deleteRecord.setDeleteStatus(DeleteStatusEnum.DELETE.getCode());
        uploadRecordMapper.update(deleteRecord, queryWrapper);

        String imgJson = itemDetailEditDto.getImgJson();
        JSONArray objects = JSON.parseArray(imgJson);

        if(objects.size() == 0){
            throw new BackStageRuntimeException("请至少上传一张图片");
        }
        objects.forEach(item -> {
            // 新增封面图片
            UploadRecord uploadRecord = new UploadRecord();
            uploadRecord.setBusinessId(itemDetail.getId());
            String[] imgArr = StringUtil.splits(item.toString(), Const.IMG_SPLIT);
            uploadRecord.setPath(imgArr[1]);
            uploadRecord.setBusinessType(BusinessTypeEnum.ITEM_COVER.getValue());
            uploadRecordMapper.insert(uploadRecord);
        });


        String detailImgJson = itemDetailEditDto.getDetailImgJson();
        JSONArray detailObjects = JSON.parseArray(detailImgJson);

        if(detailObjects.size() == 0){
            throw new BackStageRuntimeException("请至少上传一张详情图片");
        }
        detailObjects.forEach(item -> {
            // 新增封面图片
            UploadRecord uploadRecord = new UploadRecord();
            uploadRecord.setBusinessId(itemDetail.getId());
            String[] imgArr = StringUtil.splits(item.toString(), Const.IMG_SPLIT);
            uploadRecord.setPath(imgArr[1]);
            uploadRecord.setBusinessType(BusinessTypeEnum.DETAIL.getValue());
            uploadRecordMapper.insert(uploadRecord);
        });
        return itemDetail.getId();
    }

    /**
     * 删除产品
     *
     * @param idDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long deleteItemDetail(IdDto idDto) {
        itemDetailMapper.deleteById(idDto.getId());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("business_id", idDto.getId());
        UploadRecord deleteRecord = new UploadRecord();
        deleteRecord.setDeleteStatus(DeleteStatusEnum.DELETE.getCode());
        uploadRecordMapper.update(deleteRecord, queryWrapper);
        return idDto.getId();
    }

    /**
     * 根据id查询产品
     *
     * @param idDto
     */
    @Override
    public ItemDetailVo selectItemDetailById(IdDto idDto) {
        ItemDetail itemDetail = itemDetailMapper.selectById(idDto.getId());
        ItemDetailVo itemDetailVo = new ItemDetailVo();
        BeanUtil.copyProperties(itemDetail, itemDetailVo);

        List<UploadRecord> uploadRecords = uploadService.queryUploadRecordByBusinessId(idDto.getId());
        List<ImgVo> coverList = new ArrayList<>();
        List<ImgVo> detailList = new ArrayList<>();

        uploadRecords.stream().filter(predicate
                -> BusinessTypeEnum.ITEM_COVER.getValue().equals(predicate.getBusinessType()))
                .forEach(item -> {
            ImgVo imgVo = new ImgVo();
            imgVo.setId(String.valueOf(item.getId()));
            imgVo.setPath(item.getPath());
            coverList.add(imgVo);
        });

        uploadRecords.stream().filter(predicate
                -> BusinessTypeEnum.DETAIL.getValue().equals(predicate.getBusinessType()))
                .forEach(item -> {
                    ImgVo imgVo = new ImgVo();
                    imgVo.setId(String.valueOf(item.getId()));
                    imgVo.setPath(item.getPath());
                    detailList.add(imgVo);
                });

        itemDetailVo.setImgVo(coverList);
        itemDetailVo.setDetailImgVo(detailList);
        return itemDetailVo;
    }


}
